const { User, Order, Car, Review, Verification } = require('../models');
const mongoose = require('mongoose');
const { manualCheckOrders } = require('../scripts/scheduleTasks');

// 用户管理相关功能
// 获取所有用户列表
exports.getAllUsers = async (req, res) => {
    try {
        const { page = 1, limit = 10, username, phone, email, role } = req.query;

        // 构建查询条件
        const query = {};
        if (username) query.username = new RegExp(username, 'i');
        if (phone) query.phone = new RegExp(phone, 'i');
        if (email) query.email = new RegExp(email, 'i');
        if (role) query.role = role;

        // 执行查询
        const users = await User.find(query)
            .select('-password') // 不返回密码字段
            .skip((page - 1) * limit)
            .limit(parseInt(limit))
            .sort({ createdAt: -1 });

        // 获取总数
        const total = await User.countDocuments(query);

        res.status(200).json({
            success: true,
            data: {
                users,
                pagination: {
                    total,
                    page: parseInt(page),
                    limit: parseInt(limit),
                    pages: Math.ceil(total / limit)
                }
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取用户列表失败',
            error: error.message
        });
    }
};

// 获取单个用户详情
exports.getUserById = async (req, res) => {
    try {
        const { id } = req.params;

        const user = await User.findById(id)
            .select('-password')
            .populate('verification');

        if (!user) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        res.status(200).json({
            success: true,
            data: user
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取用户详情失败',
            error: error.message
        });
    }
};

// 创建用户
exports.createUser = async (req, res) => {
    try {
        const { username, password, email, phone, role = 'user' } = req.body;

        // 检查用户是否已存在
        const existingUser = await User.findOne({
            $or: [
                { username },
                { email },
                { phone }
            ]
        });

        if (existingUser) {
            return res.status(400).json({
                success: false,
                message: '用户名、邮箱或手机号已被注册'
            });
        }

        // 创建新用户
        const user = await User.create({
            username,
            password,
            email,
            phone,
            role
        });

        res.status(201).json({
            success: true,
            message: '用户创建成功',
            data: {
                id: user._id,
                username: user.username,
                email: user.email,
                phone: user.phone,
                role: user.role
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '创建用户失败',
            error: error.message
        });
    }
};

// 更新用户信息
exports.updateUser = async (req, res) => {
    try {
        const { id } = req.params;
        const { username, email, phone, role, isVerified } = req.body;

        // 构建更新对象
        const updateData = {};
        if (username) updateData.username = username;
        if (email) updateData.email = email;
        if (phone) updateData.phone = phone;
        if (role) updateData.role = role;
        if (isVerified !== undefined) updateData.isVerified = isVerified;

        // 更新用户
        const user = await User.findByIdAndUpdate(
            id,
            updateData,
            { new: true, runValidators: true }
        ).select('-password');

        if (!user) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        res.status(200).json({
            success: true,
            message: '用户信息更新成功',
            data: user
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '更新用户失败',
            error: error.message
        });
    }
};

// 删除用户
exports.deleteUser = async (req, res) => {
    try {
        const { id } = req.params;

        // 检查是否为管理员自己
        if (id === req.user.userinfo.id) {
            return res.status(400).json({
                success: false,
                message: '不能删除当前登录的管理员账户'
            });
        }

        const user = await User.findByIdAndDelete(id);

        if (!user) {
            return res.status(404).json({
                success: false,
                message: '用户不存在'
            });
        }

        res.status(200).json({
            success: true,
            message: '用户删除成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '删除用户失败',
            error: error.message
        });
    }
};

// 订单管理相关功能
// 获取所有订单
exports.getAllOrders = async (req, res) => {
    try {
        const {
            page = 1,
            limit = 10,
            status,
            userId,
            carId,
            startDate,
            endDate,
            orderNumber
        } = req.query;

        // 构建查询条件
        const query = {};
        if (status) query.status = status;
        if (userId) query.userId = userId;
        if (carId) query.carId = carId;
        if (orderNumber) query.orderNumber = new RegExp(orderNumber, 'i');

        // 日期范围查询
        if (startDate || endDate) {
            query.createdAt = {};
            if (startDate) query.createdAt.$gte = new Date(startDate);
            if (endDate) query.createdAt.$lte = new Date(endDate);
        }

        // 执行查询
        const orders = await Order.find(query)
            .populate('userId', 'username phone email')
            .populate('carId', 'brand model coverImage')
            .skip((page - 1) * limit)
            .limit(parseInt(limit))
            .sort({ createdAt: -1 });

        // 获取总数
        const total = await Order.countDocuments(query);

        res.status(200).json({
            success: true,
            data: {
                orders,
                pagination: {
                    total,
                    page: parseInt(page),
                    limit: parseInt(limit),
                    pages: Math.ceil(total / limit)
                }
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取订单列表失败',
            error: error.message
        });
    }
};

// 获取订单详情
exports.getOrderById = async (req, res) => {
    try {
        const { id } = req.params;

        const order = await Order.findById(id)
            .populate('userId', 'username phone email')
            .populate('carId', 'brand model coverImage specifications');

        if (!order) {
            return res.status(404).json({
                success: false,
                message: '订单不存在'
            });
        }

        res.status(200).json({
            success: true,
            data: order
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取订单详情失败',
            error: error.message
        });
    }
};

// 更新订单
exports.updateOrder = async (req, res) => {
    try {
        const { id } = req.params;
        const {
            status,
            startTime,
            endTime,
            pickupLocation,
            returnLocation,
            totalAmount,
            rentalFee,
            insuranceFee,
            deposit,
            additionalServices,
            remarks
        } = req.body;

        // 构建更新对象
        const updateData = {};
        if (status) updateData.status = status;
        if (startTime) updateData.startTime = startTime;
        if (endTime) updateData.endTime = endTime;
        if (pickupLocation) updateData.pickupLocation = pickupLocation;
        if (returnLocation) updateData.returnLocation = returnLocation;
        if (totalAmount) updateData.totalAmount = totalAmount;
        if (rentalFee) updateData.rentalFee = rentalFee;
        if (insuranceFee) updateData.insuranceFee = insuranceFee;
        if (deposit) updateData.deposit = deposit;
        if (additionalServices) updateData.additionalServices = additionalServices;
        if (remarks) updateData.remarks = remarks;

        // 更新订单
        const order = await Order.findByIdAndUpdate(
            id,
            updateData,
            { new: true, runValidators: true }
        );

        if (!order) {
            return res.status(404).json({
                success: false,
                message: '订单不存在'
            });
        }

        // 如果订单状态变更为已完成或已取消，更新车辆状态
        if (status === '已完成' || status === '已取消') {
            await Car.findByIdAndUpdate(order.carId, {
                status: '可租'
            });
        } else if (status === '进行中') {
            await Car.findByIdAndUpdate(order.carId, {
                status: '已租'
            });
        }

        res.status(200).json({
            success: true,
            message: '订单更新成功',
            data: order
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '更新订单失败',
            error: error.message
        });
    }
};

// 删除订单
exports.deleteOrder = async (req, res) => {
    try {
        const { id } = req.params;

        // 查找订单
        const order = await Order.findById(id);

        if (!order) {
            return res.status(404).json({
                success: false,
                message: '订单不存在'
            });
        }

        // 如果订单状态为进行中，需要更新车辆状态
        if (order.status === '进行中') {
            await Car.findByIdAndUpdate(order.carId, {
                status: '可租'
            });
        }

        // 删除订单
        await Order.findByIdAndDelete(id);

        res.status(200).json({
            success: true,
            message: '订单删除成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '删除订单失败',
            error: error.message
        });
    }
};

// 评论管理相关功能
// 获取所有评论
exports.getAllReviews = async (req, res) => {
    try {
        const { page = 1, limit = 10, userId, carId } = req.query;

        // 构建查询条件
        const query = {};
        if (userId) query.userId = userId;
        if (carId) query.carId = carId;

        // 执行查询
        const reviews = await Review.find(query)
            .populate('userId', 'username')
            .populate('carId', 'brand model')
            .skip((page - 1) * limit)
            .limit(parseInt(limit))
            .sort({ createdAt: -1 });

        // 获取总数
        const total = await Review.countDocuments(query);

        res.status(200).json({
            success: true,
            data: {
                reviews,
                pagination: {
                    total,
                    page: parseInt(page),
                    limit: parseInt(limit),
                    pages: Math.ceil(total / limit)
                }
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取评论列表失败',
            error: error.message
        });
    }
};

// 删除评论
exports.deleteReview = async (req, res) => {
    try {
        const { id } = req.params;

        const review = await Review.findByIdAndDelete(id);

        if (!review) {
            return res.status(404).json({
                success: false,
                message: '评论不存在'
            });
        }

        res.status(200).json({
            success: true,
            message: '评论删除成功'
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '删除评论失败',
            error: error.message
        });
    }
};

// 更新评论
exports.updateReview = async (req, res) => {
    try {
        const { id } = req.params;
        const { rating, comment } = req.body;

        // 构建更新对象
        const updateData = {};
        if (rating) updateData.rating = rating;
        if (comment) updateData.comment = comment;

        // 更新评论
        const review = await Review.findByIdAndUpdate(
            id,
            updateData,
            { new: true, runValidators: true }
        );

        if (!review) {
            return res.status(404).json({
                success: false,
                message: '评论不存在'
            });
        }

        // 更新车辆的平均评分
        const reviews = await Review.find({ carId: review.carId });
        let totalRating = 0;
        reviews.forEach(rev => {
            totalRating += rev.rating;
        });
        const averageRating = totalRating / reviews.length;

        await Car.findByIdAndUpdate(review.carId, {
            'rentalHistory.averageRating': averageRating
        });

        res.status(200).json({
            success: true,
            message: '评论更新成功',
            data: review
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '更新评论失败',
            error: error.message
        });
    }
};

// 手动触发订单状态检查
exports.checkOverdueOrders = async (req, res) => {
    try {
        const result = await manualCheckOrders();

        res.status(200).json({
            success: true,
            message: `订单检查完成，已处理 ${result.completedOrders} 个超时订单`,
            data: result
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '订单检查失败',
            error: error.message
        });
    }
};

// 获取认证审核列表
exports.getVerifications = async (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const limit = parseInt(req.query.limit) || 10;
        const verified = req.query.verified ? req.query.verified === 'true' : undefined;

        const query = {};
        if (verified !== undefined) {
            query.verified = verified;
        }

        const verifications = await Verification.find(query)
            .populate('userId', 'id username')
            .sort({ createdAt: -1 })
            .skip((page - 1) * limit)
            .limit(limit);

        const total = await Verification.countDocuments(query);

        res.json({
            success: true,
            data: {
                verifications,
                pagination: {
                    total,
                    page,
                    limit,
                    pages: Math.ceil(total / limit)
                }
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '获取认证列表失败',
            error: error.message
        });
    }
};

// 更新认证审核状态
exports.updateVerification = async (req, res) => {
    try {
        const { id } = req.params;
        const { verified, remarks } = req.body;

        if (verified === undefined) {
            return res.status(400).json({
                success: false,
                message: '审核状态不能为空'
            });
        }

        const verification = await Verification.findById(id);
        if (!verification) {
            return res.status(404).json({
                success: false,
                message: '认证记录不存在'
            });
        }

        verification.verified = verified;
        if (remarks) {
            verification.remarks = remarks;
        }

        await verification.save();

        res.json({
            success: true,
            message: '审核完成',
            data: {
                id: verification._id,
                userId: verification.userId,
                realName: verification.realName,
                idNumber: verification.idNumber,
                verified: verification.verified,
                remarks: verification.remarks
            }
        });
    } catch (error) {
        res.status(500).json({
            success: false,
            message: '审核失败',
            error: error.message
        });
    }
};